<template>
  <div class="app-container">
    <el-form :model="templateParams" ref="queryForm" inline size="small" label-width="68px">
      <el-form-item label="分类:" prop="catalog">
        <el-select v-model="templateParams.catalog" placeholder="请选择分类" clearable>
          <el-option v-for="item in catalogOption" :key="item.value" :value="item.value" :label="item.label"/>
        </el-select>
      </el-form-item>
      <el-form-item label="名称:" prop="name">
        <el-input v-model="templateParams.name" placeholder="请输入名称" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          icon="el-icon-plus"
          v-hasPermi="['tool:gen:template:add']"
          @click="tableAction('add', {})"
        >
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          size="mini"
          icon="el-icon-delete"
          :disabled="!selectTel.length"
          v-hasPermi="['tool:gen:template:remove']"
          @click="tableAction('deleteSelect')"
        >
          批量删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          :disabled="selectTel.length < 1"
          v-hasPermi="['tool:gen:template:preview']"
          @click="tableAction( 'template')"
        >
          模板生成
        </el-button>
      </el-col>
      <el-col :span="1.5" style="float: right">
        <el-link class="link-style" :underline="false" @click="templateCourse">
          Velocity模板语法教程<i class="el-icon-s-promotion"/>
        </el-link>
      </el-col>
    </el-row>
    <el-table v-loading="tableLoading" :data="tableData" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"/>
      <el-table-column
        v-for="col in tableCol"
        :key="col.prop"
        :prop="col.prop"
        :label="col.label"
        :width="col.width"
        show-overflow-tooltip
        align="center"
      >
        <template #default="scope">
          <span v-if="col.prop == 'catalog'">{{ getCatalogLabel(scope.row[col.prop]) }}</span>
          <span v-else>{{ scope.row[col.prop] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class="no-select">
        <template #default="scope">
          <el-button
            type="text"
            size="small"
            v-hasPermi="['tool:gen:template:edit']"
            @click="tableAction('edit',scope.row)"
          >
            修改
          </el-button>
          <el-button
            type="text"
            size="small"
            style="color: #13227a"
            v-hasPermi="['tool:gen:template:params']"
            @click="tableAction('bindParams',scope.row)"
          >
            配置参数
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="templateParams.pageNum"
      :limit.sync="templateParams.pageSize"
      @pagination="getTemplateList"
    />
    <!-- 编辑模板 -->
    <SaveTemplate ref="SaveTemplate" :catalog-option="catalogOption" @flushData="getTemplateList"/>
    <!-- 配置模板参数 -->
    <BindParams ref="BindParams" @flushData="getTemplateList"/>
    <!-- 模板生成前的参数配置 -->
    <el-dialog
      title="参数配置"
      :visible.sync="paramsDialog"
      :close-on-click-modal="false"
      top="2vh"
      width="80%"
      @close="paramsDialog = false"
    >
      <el-tabs v-if="paramsDialog" v-model="tabValue">
        <el-tab-pane
          v-for="tel in genTemplate"
          :key="tel.id + ''"
          :label="tel.name"
          :name="tel.id + ''"
        >
          <div style="height: 58vh;overflow: hidden auto">
            <TemplateParams
              v-if="tabValue == tel.id + ''"
              :ref="'TemplateParams' + tel.id"
              :default-data="tel.paramsList"
              @paramChange="val => paramChange(tel, val)"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="paramsDialog = false">关 闭</el-button>
        <el-button type="primary" size="small" :loading="createLoading" @click="generateCode">
          确 定
        </el-button>
      </span>
    </el-dialog>
    <!-- 模板生成的代码预览 -->
    <el-dialog
      title="代码预览"
      :visible.sync="resultDialog"
      :close-on-click-modal="false"
      top="2vh"
      width="80%"
      @close="resultDialog = false"
    >
      <GenerateResult ref="GenerateResultList" :result="genResult"/>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resultDialog = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import SaveTemplate from "@/views/tool/genTemplate/components/SaveTemplate";
import TemplateParams from "@/views/tool/genTemplate/components/TemplateParams";
import GenerateResult from "@/views/tool/genTemplate/components/GenerateResult";
import {TEMPLATE_COL, TEL_TYPE} from "@/views/tool/genTemplate/toolConstants";
import BindParams from "@/views/tool/genTemplate/components/BindParams";
import {deleteTemplate, fetchTemplate, previewCode} from "@/api/tool/genTemplate";
import {cloneDeep} from "lodash-es";

export default {
  name: "TemplateTool",
  components: {SaveTemplate, BindParams, TemplateParams, GenerateResult},
  data() {
    return {
      tableData: [],
      tableCol: TEMPLATE_COL,
      templateParams: {
        name: null,
        catalog: null,
        pageNum: 1,
        pageSize: 10
      },
      tableLoading: false,
      paramsDialog: false,
      createLoading: false,
      resultDialog: false,
      tabValue: '',
      total: 0,
      catalogOption: TEL_TYPE,
      selectTel: [],
      genTemplate: [],
      genResult: {}
    }
  },
  created() {
    this.getTemplateList()
  },
  methods: {
    // 搜索方法
    handleQuery() {
      this.templateParams.pageNum = 1
      this.templateParams.pageSize = 10
      this.getTemplateList()
    },
    // 重置查询条件和分页参数
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery()
    },
    // 查询数据
    getTemplateList() {
      this.tableLoading = true
      fetchTemplate(this.templateParams).then(res => {
        this.tableData = res.rows
        this.total = res.total
      }).finally(() => this.tableLoading = false)
    },
    // 表格操作按钮
    tableAction(type, rowData) {
      switch (type) {
        case 'add':
        case 'edit': {
          this.$refs.SaveTemplate.openDialog(rowData)
          break
        }
        case 'bindParams': {
          this.$refs.BindParams.openDialog(rowData)
          break
        }
        case 'deleteSelect': {
          if (this.selectTel.length) {
            this.$confirm('是否删除模板？', '提示', {
              confirmButtonText: '确认',
              type: 'warning',
              showClose: false, // 是否显示右上角的x
              closeOnClickModal: false, // 是否可以点击空白处关闭弹窗
            }).then(() => {
              const delId = this.selectTel.map(item => item.id)
              deleteTemplate(delId).then(() => {
                this.$message.success("删除成功")
                this.getTemplateList()
              })
            })
          }
          break
        }
        case 'template':
          this.paramsDialog = true
          this.genTemplate = cloneDeep(this.selectTel)
          this.tabValue = this.genTemplate[0].id + ''
          break
      }
    },
    // 表格选中触发
    handleSelectionChange(selection) {
      if (selection && selection.length) {
        this.selectTel = cloneDeep(selection)
      } else {
        this.selectTel = []
      }
    },
    // 分类名称
    getCatalogLabel(val) {
      const target = this.catalogOption.find(item => item.value == val)
      return target ? target.label : val
    },
    // 模板参数配置时，参数改变触发
    paramChange(tel, val) {
      this.$set(tel, 'paramsList', val)
    },
    // 临时模板结果生成
    generateCode() {
      this.genResult = {}
      this.createLoading = true
      const templateArr = []
      templateArr.push(...this.genTemplate)
      previewCode(templateArr).then(res => {
        this.genResult = res.data
        this.paramsDialog = false
        this.resultDialog = true
      }).finally(() => this.createLoading = false)
    },
    // 跳转教程页面
    templateCourse() {
      window.open('https://www.cnblogs.com/wywblogs/articles/18036276', '_blank');
    }
  }
}
</script>
<style scoped>
.link-style {
  font-weight: bolder;
  color: cadetblue;
}
</style>
